package com.ljfresh.customer.sercice.common.Impl;

import com.ljfresh.customer.page.PageObject;
import com.ljfresh.customer.page.PageResult;
import com.ljfresh.customer.mapper.common.CommonMapper;
import com.ljfresh.customer.sercice.common.CommonService;
import com.ljfresh.customer.utils.ParamMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author: Lucifer
 * @time: 2020/4/9-15:44
 */
@Transactional
public class CommonServiceImpl<T , PK > implements CommonService<T, PK> {

    /** CommonMapper */
    @Autowired
    private CommonMapper<T, PK> genericMapper;

    public void setCommonMapper(CommonMapper<T, PK> genericMapper) {
        this.genericMapper = genericMapper;
    }


    @Transactional
    public Long save(T param) {
        return genericMapper.insert(param);
    }

    @Transactional
    public Long update(T param) {
        return genericMapper.update(param);
    }

    @Transactional
    public Long delete(PK pk) {
        return genericMapper.delete(pk);
    }

    @Transactional
    public Long deleteAll(Long ... ids) {
        return genericMapper.deleteAll(ParamMap.create().put("ids", ids)); }

    @Transactional(readOnly = true)
    public Long count() {
        return genericMapper.count();
    }

    @Transactional(readOnly = true)
    public Long count(Map<String, Object> params) {
        return genericMapper.count(params);
    }

    @Transactional(readOnly = true)
    public T find(PK pk) {
        return genericMapper.find(pk);
    }

    @Transactional(readOnly = true)
    public List<T> findAll() {
        return genericMapper.findAll();
    }


    @Transactional(readOnly = true)
    public PageResult<T> findByPage(PageObject po){
        List<T> byPage = genericMapper.findByPage(po);
        PageResult<T> result = new PageResult<T>();
        result.setList(byPage);
        result.setPageNum(po.getPageNumber()+1);
        result.setPageSize(po.getPageSize());
        Long count = genericMapper.count(po.getMap());
        result.setTotalCount(count.intValue());
        return result;
    }

    @Transactional(readOnly = true)
    public T find(String propertyName, Object value) {
        List<T> results = genericMapper.findByParams(ParamMap.create().put(propertyName, value));
        //不为空
        if(!CollectionUtils.isEmpty(results)){
            return results.get(0);
        }
        return null;
    }

    @Transactional(readOnly = true)
    public List<T> findList(String propertyName, Object value) {
        List<T> results = genericMapper.findByParams(ParamMap.create().put(propertyName, value));
        return results;
    }

    @Transactional(readOnly = true)
    public List<T> findList(Map<String, Object> params) {
        return genericMapper.findByParams(params);
    }
}
